from sqlalchemy import (
    create_engine,
    inspect,
    Column,
    String,
)
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.types import TypeDecorator
from datetime import datetime
import uuid
from constants import DbConfig

# Custom TypeDecorator to store datetimes as ISO 8601 strings
class IsoDateTime(TypeDecorator):
    """
    Stores Python datetime objects as ISO-8601 strings in the database.
    This is a robust way to handle datetimes in SQLite.
    """
    impl = String
    cache_ok = True

    def process_bind_param(self, value, dialect):
        if isinstance(value, datetime):
            return value.isoformat().replace('T', ' ')
        return value

    def process_result_value(self, value, dialect):
        if value is not None:
            # The datetime.fromisoformat method can handle a space as a separator
            if value.startswith('v'):
                value = value[1:]
            return datetime.fromisoformat(value)
        return value

Base = declarative_base()

def to_camel_case(snake_str):
    components = snake_str.split('_')
    return components[0] + ''.join(x.title() for x in components[1:])

def to_dict(self):
    d = {}
    for column in self.__table__.columns:
        value = getattr(self, column.name)
        if isinstance(value, datetime):
            d[to_camel_case(column.name)] = value.isoformat().replace('T', ' ')
        else:
            d[to_camel_case(column.name)] = value
    return d

Base.to_dict = to_dict

engine = create_engine(DbConfig.DATABASE_URL, echo=True)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def create_db():
    Base.metadata.create_all(bind=engine)

